Page({
  data: {
    houseList: [], // 房源列表
    isEmpty: false, // 是否为空
    dialogVisible: false,
  },

  onShow() {
    this.getHouseList()
  },

  async getHouseList() {
    // 调用接口
    await wx.http.get('/room').then((res) => {
      if (res.code !== 10000) return wx.utils.messagePrompt()
      this.setData({
        houseList: res.data,
        isEmpty: res.data.length === 0,
      })
    })
  },

  swipeClose(ev) {
    console.log(ev)
    const { position, instance } = ev.detail

    if (position === 'right') {
      // 显示 Dialog 对话框
      this.setData({
        dialogVisible: true,
      })

      this.cellId = ev.mark.id
      this.cellIndex = ev.mark.index

      // swiper-cell 滑块关闭
      instance.close()
    }
  },

  dialogClose(ev) {
    // console.log(ev)
    if (ev.detail === 'confirm') {
      this.deleteHouse()
    }
  },

  async deleteHouse() {
    if (!this.cellId) return wx.utils.messagePrompt('请选择要删除的房源!')
    await wx.http
      .delete('/room/' + this.cellId)
      .then((res) => {
        if (res.code !== 10000) return wx.utils.messagePrompt()
        wx.utils.messagePrompt('删除成功!')
        this.setData({
          houseList: this.data.houseList.filter((item) => item.id !== this.cellId),
          isEmpty: this.data.houseList.length === 0,
        })
      })
      .catch((err) => {
        wx.utils.messagePrompt('删除失败!')
      })
  },

  goDetail(ev) {
    const id = ev.mark?.id
    wx.navigateTo({
      url: '/house_pkg/pages/detail/index?id=' + id,
    })
  },

  addHouse() {
    wx.navigateTo({
      url: '/house_pkg/pages/locate/index',
    })
  },
})
